package com.apk.tools;

import java_util.coo_util.C_File;
import java_util.coo_util.Log.C_Log;

import java.io.*;
import java.net.URL;
import java.util.Random;

public class C_IpaUtil {
    public static String xcodeTemplateName = "/xcodeTemplate.zip";
    public final static String embedded = "/embedded.mobileprovision";
    public static String temp_buildXcodeTemplate = "temp_buildXcodeTemplate.sh";


    ///拷贝Xcode模板
    public static String S_CopyXcodeTemplate(String _buildPath) throws IOException {
        String path = _buildPath + xcodeTemplateName;
        S_fileCopy(xcodeTemplateName, path);
        String path0 = _buildPath + "/xcodeTemplate";
        C_cmd.S_delete(path0);
        C_cmd.S_Runtime("unzip -d " + path0 + " " + path);

        S_fileCopy(embedded + ".txt", _buildPath + embedded);

        return path0;
    }

    public static void S_DelectXcodeTemplate(String _buildPath) throws IOException {
        String path = _buildPath + xcodeTemplateName;

        C_cmd.S_delete(_buildPath + embedded);
        C_cmd.S_delete(path);
        C_cmd.S_delete(_buildPath + "/xcodeTemplate");
    }

    public boolean exists() {
        URL resource = C_IpaUtil.class.getResource(xcodeTemplateName);
        if (resource == null) {
            return false;
        }
        File f = new File(resource.getFile());
        return f.exists();
    }

    //拷贝文件
    public static void S_fileCopy(String sourcePath, String targetPath) throws IOException {
        URL resource = C_IpaUtil.class.getResource(sourcePath);
        if (resource == null) {
            C_Log.LogFormat("S_fileCopy.jar内部资源.....resource==null.%s.......", sourcePath);
            return;
        }
        C_Log.LogFormat("开始Copy.jar内部资源....%s........%s", sourcePath, targetPath);
        int n = 0;
        try {
            InputStream inputStream2 = resource.openStream();
            FileOutputStream target = new FileOutputStream(targetPath);
            while ((n = inputStream2.read()) != -1) {
                target.write(n);
            }
            inputStream2.close();
            target.close();
        } catch (FileNotFoundException e) {
            C_Log.LogException("S_fileCopy.1.错误...", e);
            // e.printStackTrace();
        } catch (IOException e) {
            C_Log.LogException("S_fileCopy.2.错误...", e);
            //e.printStackTrace();
        }
    }


    ///构建模板
    public static void S_buildXcodeTemplate(String rootPath, String _unzipRootPath, build_config setting) throws IOException {
        String path = rootPath + temp_buildXcodeTemplate;
        C_cmd.S_delete(path);

        S_fileCopy("/" + temp_buildXcodeTemplate, path);


        //S_copyFile_ReplacTextContent(path + ".txt", path, , _unzipRootPath);
        C_cmd.S_Runtime("chmod 777 " + path);
        C_cmd.S_Runtime("/usr/local/bin/dos2unix " + path);
        //C_cmd.S_delete(path + ".txt");
        String _xcode_ProjectPath0 = rootPath + build_config._build + "/" + "xcodeTemplate/";
        String _xcode_ProjectPath = rootPath + build_config._build + "/" + setting.temp_package;
        C_cmd.S_delete(_xcode_ProjectPath);

        S_copyDir_Rename(_xcode_ProjectPath0, _xcode_ProjectPath, (rootPath + build_config._build).length(), "xcodeTemplate", setting.temp_package);

        String _outputPath = rootPath + build_config._build + "/" + setting.temp_package + ".xcarchive";
        C_cmd.S_delete(_outputPath);

        C_cmd.S_Runtime(new String[]{path, _xcode_ProjectPath, _outputPath, setting.temp_package});

        C_File.S_copyFile(_outputPath + "/Products/Applications/" + setting.temp_package + ".app/Assets.car", _unzipRootPath + "/Assets.car");
        ///C_File.S_copyFile(_outputPath + "/Products/Applications/xcodeTemplate.app/xcodeTemplate", _unzipRootPath + "/pingtai");
        //C_File.S_copyFile(_outputPath + "/Products/Applications/xcodeTemplate.app/PkgInfo", _unzipRootPath + "/PkgInfo");
        //C_File.S_copyFile(_outputPath + "/Products/Applications/xcodeTemplate.app/pingtai", _unzipRootPath + "/pingtai");
        //C_cmd.S_delete(path);

    }


    public static void S_copyFile_ReplacTextContent(String oldPath, String targetPath, String buildPath, String unzipRootPath) throws IOException {

        int ran2 = C_cmd.getProcessID();
        // 读
        //File file = new File(path);
        //FileReader in = new FileReader(file);
        BufferedReader bufIn = new BufferedReader(new FileReader(new File(oldPath)));
        // 内存流, 作为临时流
        CharArrayWriter tempStream = new CharArrayWriter();
        // 替换
        String line = null;
        while ((line = bufIn.readLine()) != null) {
            // 替换每行中, 符合条件的字符串
            line = line.replace("➜", buildPath);
            line = line.replace("✪", unzipRootPath);
            line = line.replace("▼", ran2 + "");
            // 将该行写入内存
            tempStream.write(line);
            // 添加换行符
            tempStream.append(System.getProperty("line.separator"));
        }
        // 关闭 输入流
        bufIn.close();
        // 将内存中的流 写入 文件
        FileWriter out = new FileWriter(new File(targetPath));
        tempStream.writeTo(out);
        out.close();
        C_Log.LogWarningFormat("xcode构建:.......%d........%s", ran2, oldPath);
    }

    //拷贝文件
    public static boolean S_copyDir_Rename(String oldPath, String newPath, int startIndex, String oblName, String newName) throws IOException {
        C_Log.LogFormat("拷贝改名目录.....%s........%s....%d...%s...%s", oldPath, newPath, startIndex, oblName, newName);
        boolean result = true;
        String[] filePaths = new File(oldPath).list();

        if (filePaths != null && filePaths.length > 0) {
            if (!new File(newPath).exists()) {
                if (!new File(newPath).mkdirs()) {
                    C_Log.error("文件夹创建失败");
                    return false;
                }
            }
            try {
                for (String filePath : filePaths) {
                    String taargetPath = newPath + File.separator + filePath;
                    String aa = taargetPath.substring(0, startIndex);
                    String bb = taargetPath.substring(startIndex).replace(oblName, newName);
                    taargetPath = aa + bb;
                    C_Log.Log("文件............" + filePath);
                    if (new File(oldPath + File.separator + filePath).isDirectory()) {
                        S_copyDir_Rename(oldPath + File.separator + filePath, taargetPath, startIndex, oblName, newName);
                    } else if (new File(oldPath + File.separator + filePath).isFile()) {
                        if (filePath.equals("project.pbxproj") || filePath.equals("xcschememanagement.plist")) {
                            C_File.S_copyFile_ReplacTextContent(oldPath + File.separator + filePath, taargetPath, oblName, newName);
                        } else {
                            //复制文件到另一个目录
                            C_File.S_copyFile(oldPath + File.separator + filePath, taargetPath);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
